import re

from django.conf import settings
from django.core.mail import send_mail
from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from users.models import User
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from celery_tasks.email.tasks import send_email
class UserSerializers(serializers.ModelSerializer):
    # 显示指明模型类中没有的字段
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(write_only=True)

    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('username', 'password', 'password2', 'mobile', 'allow', 'sms_code', 'id', 'token')
        extra_kwargs = {
            'password':
                {
                    'max_length': 20,
                    'min_length': 8,
                    'write_only': True
                },
            'username':
                {
                    'max_length': 20,
                    'min_length': 5,
                }
        }

    # 验证手机号格式
    def validate_mobile(self, value):

        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式不匹配')

        return value

    # 验证选中状态
    def validate_allow(self, value):

        if value != 'true':
            raise serializers.ValidationError('协议未同意')

        return value

    # 验证两次密码和短信验证
    def validate(self, attrs):
        # 密码判度
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断用户名是否是手机格式
        if re.match(r'^1[3-9]\d{9}$', attrs['username']):
            if attrs['username'] != attrs['mobile']:
                raise serializers.ValidationError('用户名和手机号不一致')

        # 1、获取缓存中真实的短信验证码
        conn = get_redis_connection('sms_code')
        real_sms_code = conn.get('sms_code_$%s' % attrs['mobile'])
        # 2、判断短信验证码是否失效
        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码已失效')
        # 3、比对用户输入的短信验证码
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('输入的短信验证码错误')
        return attrs

    # 保存
    def create(self, validated_data):

        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        print(validated_data)
        #
        # user=User.objects.create_user(validated_data)

        user = User.objects.create_user(username=validated_data['username'], password=validated_data['password'],
                                        mobile=validated_data['mobile'])

        # User.objects.create() # 不会对密码进行加密



        # 生成jwt token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 给user对象添加token属性
        user.token = token

        return user


class UserShowSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'mobile', 'email', 'id', 'email_active')


class UserEmailSerializers(serializers.Serializer):
    email = serializers.EmailField()

    def update(self, instance, validated_data):
        tjs = TJS(settings.SECRET_KEY, 300)
        token = tjs.dumps({'username':instance.username}).decode()
        to_email = validated_data['email']
        send_email.delay(token, to_email)
        instance.email = validated_data['email']
        instance.save()
        return instance
